package com.hcx.reggie.controller;

import com.hcx.reggie.service.DishService;
import com.hcx.reggie.utils.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.reactive.context.StandardReactiveWebEnvironment;
import org.springframework.context.annotation.FullyQualifiedAnnotationBeanNameGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("common")
public class FileController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传功能实现
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R<String> upLoad(MultipartFile file){
        //使用UUId来生成文件名称，防止文件名称重复，导致文件被覆盖
        String s = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = s + substring;
        File dir = new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            //将临时文件转存到指定的位置
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件下载功能实现
     * @param name
     * @param response
     */
    @GetMapping("download")
    public void downLoad(String name, HttpServletResponse response ){
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int length = 0;
            byte[] bytes = new byte[1024];
            while((length = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,length);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
